<template>
  <div id="pictureList">
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :loading="loading"
    >
      <template #renderItem="{ item: picture }">
        <a-list-item style="padding: 0">
          <a-card
            class="picture-card"
            hoverable
            @click="onPictureClick(picture)"
            @mouseover="hoveredPicture = picture.id"
            @mouseleave="hoveredPicture = null"
          >
            <template #cover>
              <div class="image-wrapper">
                <img
                  class="picture-image"
                  :class="{ 'image-darken': hoveredPicture === picture.id }"
                  :alt="picture.name"
                  :src="picture.thumbnailUrl ?? picture.url"
                />
                <div v-if="hoveredPicture === picture.id" class="button-group">
                  <a-button
                    class="download-btn"
                    type="primary"
                    @click.stop="onDownload(picture.url)"
                  >
                    立即下载
                  </a-button>
                  <!-- 仅当 showFavorite 为 true 时显示收藏按钮 -->
                  <a-button
                    v-if="showFavorite"
                    class="favorite-btn"
                    type="text"
                    @click.stop="toggleFavorite(picture.id)"
                  >
                    <StarFilled
                      v-if="favoritedPictures.has(picture.id)"
                      class="star-icon favorite"
                    />
                    <StarOutlined v-else class="star-icon" />
                  </a-button>
                </div>
              </div>
            </template>
            <a-card-meta :title="picture.name">
              <template #description>
                <a-flex>
                  <a-tag class="category-tag" color="green">
                    {{ picture.category ?? '默认' }}
                  </a-tag>
                  <a-tag v-for="tag in picture.tags" :key="tag" :color="tagColors[tag]">
                    {{ tag }}
                  </a-tag>
                </a-flex>
              </template>
            </a-card-meta>
            <template v-if="showOp" #actions>
              <a-space @click="(e) => doShare(picture, e)">
                <SearchOutlined />
                分享
              </a-space>
              <a-space @click="(e) => doEdit(picture, e)">
                <EditOutlined />
                编辑
              </a-space>
              <a-space @click="(e) => doDelete(picture, e)">
                <DeleteOutlined />
                删除
              </a-space>
            </template>
          </a-card>
        </a-list-item>
      </template>
    </a-list>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { downloadImage, initializeTagColors } from '@/utils'
import {
  StarOutlined,
  StarFilled,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import ShareModal from '@/components/ShareModal.vue'
import { message } from 'ant-design-vue'
import { deletePictureUsingDelete } from '@/apis/PictureInterface.ts'

const tagColors = reactive<Record<string, string>>({})
const hoveredPicture = ref<string | null>(null)
const favoritedPictures = ref<Set<string>>(new Set())

// 增加 showFavorite 作为可选 props
interface Props {
  dataList?: API.PictureVO[]
  tagList?: string[]
  loading: boolean
  showFavorite?: boolean
  showOp?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  tagList: () => [],
  loading: false,
  showFavorite: true, // 默认显示收藏按钮
  showOp: false, // 默认关闭操作按钮
})

watch(
  () => props.tagList,
  (newTagList) => {
    Object.assign(tagColors, initializeTagColors(newTagList))
  },
  { immediate: true },
)

const router = useRouter()
const onPictureClick = (picture) => {
  router.push({ path: `/picture/${picture.id}` })
}

// 处理下载
const loginUserStore = useLoginUserStore()
const loginUser = loginUserStore.loginUser
const onDownload = (url: string) => {
  if (!loginUser) {
    router.push('/user/login')
    return
  }
  downloadImage(url)
}

// 编辑
const doEdit = (picture, e) => {
  e.stopPropagation()
  router.push({
    path: '/edit_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

// 删除
const doDelete = async (picture, e) => {
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingDelete({ pictureId: id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 让外层刷新
    props?.onReload()
  } else {
    message.error('删除失败')
  }
}

// 收藏切换
const toggleFavorite = (pictureId: string) => {
  if (favoritedPictures.value.has(pictureId)) {
    favoritedPictures.value.delete(pictureId)
  } else {
    favoritedPictures.value.add(pictureId)
  }
}

// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()

// 分享
const doShare = (picture: API.PictureVO, e: Event) => {
  e.stopPropagation()
  //shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  shareLink.value = picture.thumbnailUrl
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}
</script>

<style scoped>
/* 图片容器 */
.image-wrapper {
  position: relative;
  overflow: hidden;
}

/* 默认图片样式 */
.picture-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  transition: filter 0.3s ease-in-out;
}

/* 鼠标悬停时变暗 */
.image-darken {
  filter: brightness(0.6);
}

/* 按钮组，右上角水平排列 */
.button-group {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  align-items: center;
  gap: 8px; /* 按钮间距 */
}

/* 下载按钮 */
.download-btn {
  font-size: 12px;
  padding: 6px 10px;
  background-color: #1890ff;
  color: white;
}

/* 收藏按钮（无背景，仅图标） */
.favorite-btn {
  padding: 0;
  border: none;
}

/* 五角星图标 */
.star-icon {
  font-size: 18px;
  color: #999;
  transition: color 0.3s;
  cursor: pointer;
}

/* 已收藏的五角星 */
.star-icon.favorite {
  color: #fadb14;
}
</style>
